/**
 * 该文件可自行根据业务逻辑进行调整
 */
import type { RequestClientOptions } from '@vben/request';

import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import {
  authenticateResponseInterceptor,
  defaultResponseInterceptor,
  errorMessageResponseInterceptor,
  RequestClient,
} from '@vben/request';
import { useAccessStore } from '@vben/stores';
import { isFunction } from '@vben/utils';
import { message } from 'ant-design-vue';

import { useAuthStore } from '#/store';
import { refreshTokenApi } from './core';

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

function createRequestClient(baseURL: string, options?: RequestClientOptions) {
  const client = new RequestClient({
    ...options,
    baseURL,
  });

  /**
   * 重新认证逻辑
   */
  async function doReAuthenticate() {
    console.warn('Access token or refresh token is invalid or expired. ');
    const accessStore = useAccessStore();
    const authStore = useAuthStore();
    accessStore.setAccessToken(null);
    if (preferences.app.loginExpiredMode === 'modal' && accessStore.isAccessChecked) {
      accessStore.setLoginExpired(true);
    } else {
      await authStore.logout();
    }
  }

  /**
   * 刷新token逻辑
   */
  async function doRefreshToken() {
    const accessStore = useAccessStore();
    const resp = await refreshTokenApi();
    const newToken = resp.data;
    accessStore.setAccessToken(newToken);
    return newToken;
  }

  function formatToken(token: null | string) {
    return token ? `Bearer ${token}` : null;
  }

  // 请求头处理
  client.addRequestInterceptor({
    fulfilled: async (config) => {
      const accessStore = useAccessStore();

      config.headers.Authorization = formatToken(accessStore.accessToken);
      config.headers['Accept-Language'] = preferences.app.locale;
      return config;
    },
  });

  // 处理返回的响应数据格式
  client.addResponseInterceptor({
    fulfilled: async (response) => {
      const { config, data: responseData, status, headers } = response;

      if (config.responseReturn === 'raw') {
        return response;
      }

      if (status >= 200 && status < 400) {
        const codeField = 'code';
        const dataField = 'data';
        const successCode = 0;
        if (config.responseType === 'blob' || headers['content-type']?.includes('application/octet-stream')) {
          // console.log('blob');
          // 🚨 关键检查：判断是否是错误JSON伪装成Blob
          if (responseData.type === 'application/json' || headers['content-type']?.includes('application/json')) {
            // 将错误Blob转换为JSON
            const errorText = await responseData.text();
            const errorData = JSON.parse(errorText);
            // 抛出转换后的错误
            throw {
              response: {
                ...response,
                data: errorData, // 替换为解析后的JSON
              },
            };
          }
          // 提取文件名
          const contentDisposition = headers['content-disposition'] || '';
          const matches = contentDisposition.match(/filename=['"]?([^'"]+)['"]?/); // 使用正则表达式匹配文件名,格式为 "filename='文件名'"
          const fileName = matches ? matches[1] : 'UnknowFile.unknown'; // 提取文件名
          // const blob = new Blob([responseData], { type: headers['content-type'] });
          return {
            blob: responseData,
            fileName: fileName,
            contentType: headers['content-type'],
          };
        } else if (config.responseReturn === 'body') {
          return responseData;
        } else if (
          isFunction(successCode) ? successCode(responseData[codeField]) : responseData[codeField] === successCode
        ) {
          return isFunction(dataField) ? dataField(responseData) : responseData[dataField];
        }
      }
      throw Object.assign({}, response, { response });
    },
    rejected: async (error) => {
      // 处理HTTP错误（4xx/5xx）
      const response = error.response;
      if (response?.data instanceof Blob && response.data.type === 'application/json') {
        // 转换错误Blob为JSON
        const errorText = await response.data.text();
        error.response.data = JSON.parse(errorText);
      }
      return Promise.reject(error);
    },
  });

  // token过期的处理
  client.addResponseInterceptor(
    authenticateResponseInterceptor({
      client,
      doReAuthenticate,
      doRefreshToken,
      enableRefreshToken: preferences.app.enableRefreshToken,
      formatToken,
    })
  );

  // 通用的错误处理,如果没有进入上面的错误处理逻辑，就会进入这里
  client.addResponseInterceptor(
    errorMessageResponseInterceptor((msg: string, error) => {
      // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理，根据不同的 code 做不同的提示，而不是直接使用 message.error 提示 msg
      // 当前mock接口返回的错误字段是 error 或者 message
      const responseData = error?.response?.data ?? {};
      const errorMessage = responseData?.error ?? responseData?.message ?? '';
      // 如果没有错误信息，则会根据状态码进行提示
      if (responseData.code === -1) {
        message.error(errorMessage || msg);
      }
    })
  );

  return client;
}

export const requestClient = createRequestClient(apiURL, {
  responseReturn: 'data',
});

export const baseRequestClient = new RequestClient({ baseURL: apiURL });

// 用于传输Blob类型数据
export const BodyRequestClient = createRequestClient(apiURL, {
  responseReturn: 'body',
});
